package org.xabber.storage.dao;

import org.xabber.storage.AbstractAccountTable;
import org.xabber.storage.DataBaseManager;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class RssTable extends AbstractAccountTable{
	private static final class Fields implements AbstractAccountTable.Fields {

		private Fields() {
		}

		public static final String RSS_NAME = "RSSNAME";

		public static final String RSS_URL = "URL";
		
		public static final String RSS_SUBSCRIPTION="subscription";

	}
	private static final String NAME = "Accounts";
	private static final String[] PROJECTION = new String[] { Fields.ACCOUNT,
			Fields.RSS_NAME, Fields.RSS_URL ,Fields.RSS_SUBSCRIPTION};
	private final DataBaseManager databaseManager;
	private SQLiteStatement writeStatement;
	private final Object writeLock;

	private final static RssTable instance;

	static {
		instance = new RssTable(DataBaseManager.getInstance());
	}

	public static RssTable getInstance() {
		return instance;
	}

	public RssTable(DataBaseManager databaseManager) {
		this.databaseManager = databaseManager;
		writeStatement = null;
		writeLock = new Object();
	}

	@Override
	public void create(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + NAME + " (" + Fields._ID
				+ " INTEGER PRIMARY KEY," + Fields.ACCOUNT + " TEXT,"
				+ Fields.RSS_NAME + " TEXT," + Fields.RSS_URL + " TEXT,"+Fields.RSS_SUBSCRIPTION+" INTEGER);";
		DataBaseManager.execSQL(db, sql);
	}

	/**
	 * Adds or updates room.
	 * 
	 * @param account
	 * @param room
	 * @param nickname
	 * @param password
	 * @param join
	 */
	void write(String account, String rssName, String url,boolean subscription) {
		synchronized (writeLock) {
			if (writeStatement == null) {
				SQLiteDatabase db = databaseManager.getWritableDatabase();
				writeStatement = db.compileStatement("INSERT OR REPLACE INTO "
						+ NAME + " (" + Fields.ACCOUNT + ", " + Fields.RSS_NAME
						+ ", " + Fields.RSS_URL + ", "+Fields.RSS_SUBSCRIPTION+") VALUES (?, ?, ?, ?);");
			}
			writeStatement.bindString(1, account);
			writeStatement.bindString(2, rssName);
			writeStatement.bindString(3, url);
			writeStatement.bindLong(4, subscription ? 1 : 0);
			writeStatement.execute();
		}
	}

	void remove(String account) {
		SQLiteDatabase db = databaseManager.getWritableDatabase();
		db.delete(NAME, Fields.ACCOUNT + " = ? ", new String[] { account });
	}

	@Override
	public String getTableName() {
		return NAME;
	}

	@Override
	protected String[] getProjection() {
		return PROJECTION;
	}
}
